package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"log"
)

// 解析 "github.com/bitly/go-simplejson" 源码
//type DataData interface {
//	Get(string) string
//}
type Data struct {
	data interface{}
}

func (d *Data) UnmarshalJSON(p []byte) error {
	dec := json.NewDecoder(bytes.NewBuffer(p))
	dec.UseNumber()
	return dec.Decode(&d.data)
}
func NewJson(body []byte) (*Data, error) {
	d := new(Data)
	err := d.UnmarshalJSON(body)
	if err != nil {
		return nil, err
	}
	return d, nil
}

// 数据转 map[string]interface{}
func (d *Data) Map() (map[string]interface{}, error) {
	if m, ok := (d.data).(map[string]interface{}); ok {
		return m, nil
	}
	return nil, errors.New("type assertion to map[string]interface{} failed")
}

// 获取相关数据
func (d Data) Get(key string) *Data {
	m, err := d.Map()
	if err == nil {
		if val, ok := m[key]; ok {
			return &Data{val}
		}
	}
	return &Data{nil}
}

func main() {
	// 不知道json格式的情况下进行拆解
	b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)

	js, err := NewJson(b)
	if err != nil {
		log.Fatal("Unmarshal json fail")
	}
	fmt.Println(js.Get("Name"))

}
